#include "choosefrienddialog.h"
#include <QScrollArea>
#include <QScrollBar>
#include <QPushButton>


#include "debug.h"
#include "choosefrienddialog.h"
#include "model/datacenter.h"
#include "toast.h"


using namespace model;


/*
 * 选择好友窗口的一个 好友项
 *
 */
ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog* owner,const QString& userId, const QIcon& avatar, const QString& name, bool checked)
    :userId(userId)
{
    //设置控件的基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    //设置布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(20,0,20,0);
    this->setLayout(layout);

    //创建复选框
    checkBox = new QCheckBox();
    checkBox->setChecked(checked);
    checkBox->setFixedSize(25,25);
    //QCheckBox::indicator用来控制 QCheckBox 的指示器部分的外观和行为
    //指示器大小：width: 20px; height: 20px; 设置复选框指示器的宽高
    //未选中状态的图片：当复选框未被选中时，显示 unchecked.png 图片。
    //选中状态的图片：当复选框被选中时，显示 checked.png 图片。
    QString style = "QCheckBox { background-color: transparent; } QCheckBox::indicator { width: 20px; height: 20px; image: url(:/resource/image/unchecked.png) }";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/checked.png); }";
    checkBox->setStyleSheet(style);

    //创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40,40);
    avatarBtn->setIconSize(QSize(40,40));
    avatarBtn->setIcon(avatar);
    avatarBtn->setStyleSheet("QPushButton { border: none; }");

    //创建名字
    nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel {background-color: transparent;}");

    //添加到布局管理器中
    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);

    //连接信号槽 如果勾选了复选框，将Item添加到右侧区域中
    connect(checkBox,&QCheckBox::toggled,this,[=](bool checked) {
        if(checked) {
            //如果勾选了复选框 添加到右侧
            owner->addSelectedFriend(userId,avatar,name);
        }else {
            // 取消勾选
            owner->deleSeletedFriend(userId);
        }
    });
}

//根据鼠标的进入状态，绘制不同的颜色
void ChooseFriendItem::paintEvent(QPaintEvent* event)
{
    (void) event;
    QPainter painter(this);
    if(isHover) {
        //将颜色加深 QRect表示要填充的矩形区域，QColor用来指定填充的颜色
        painter.fillRect(this->rect(),QColor(230,230,230));
    }else {
        //将颜色变浅
        painter.fillRect(this->rect(),QColor(255,255,255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent* event)
{
    (void) event;
    isHover = true;
    //更新界面
    this->update();

}

void ChooseFriendItem::leaveEvent(QEvent* event)
{
    (void) event;
    isHover = false;
    this->update();
}

/*
 * 选择好友的窗口
 *
 */
ChooseFriendDialog::ChooseFriendDialog(QWidget* parent,const QString& userId) :QDialog(parent),userId(userId)
{
    //设置窗口的基本属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setFixedSize(750,550);
    this->setStyleSheet("QDialog { background-color: rgb(255,255,255); }");
    this->setAttribute(Qt::WA_DeleteOnClose);

    //创建布局管理器
    QHBoxLayout* layout  = new QHBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0,0,0,0);
    this->setLayout(layout);

    //对左侧窗口进行初始化
    initLeftWindow(layout);

    //对右侧窗口进行初始化
    initRightWindow(layout);

    // 加载数据到窗口中
    initData();
}

//初始化左侧窗口
void ChooseFriendDialog::initLeftWindow(QHBoxLayout* layout)
{
    //创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    //QScrollArea 的内容是否随着窗口大小变化而自动调整尺寸
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255) }");
    scrollArea->setStyleSheet("QScrollBar { border: none; }");
    layout->addWidget(scrollArea,1);

    //创建QWidget 设置到滚动区域中
    totalContainer = new QWidget();
    totalContainer->setObjectName("totalContainer");
    totalContainer->setStyleSheet("#totalContainer { background-color: rgb(255,255,255); }");
    scrollArea->setWidget(totalContainer);

    //创建左侧子窗口的内部的布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    vlayout->setAlignment(Qt::AlignTop);
    totalContainer->setLayout(vlayout);

#if TEST_UI
    QIcon defaultAvatar(":/resource/image/avatarDefault.png");
    for(int i=0; i<5; i++) {
        this->addFriend(QString::number(100+i),defaultAvatar,"不要碧莲" + QString::number(i),false);
    }
#endif
}

//初始化右侧窗口
void ChooseFriendDialog::initRightWindow(QHBoxLayout* layout)
{
    //设置右侧布局管理器
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setSpacing(10);
    gridLayout->setContentsMargins(20,0,20,20);
    layout->addLayout(gridLayout,1);

    //创建 提示(选择联系人) label
    QLabel* tipLabel = new QLabel();
    tipLabel->setText("选择联系人");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignCenter | Qt::AlignTop);
    tipLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 700}");

    //创建滚动区
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255);}");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal {height: 0px;}");
    scrollArea->setStyleSheet("QScrollArea { border: none; }");
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    //创建滚动区中的QWidget
    selectedContainer = new QWidget();
    selectedContainer->setObjectName("#selectedContainer");
    selectedContainer->setStyleSheet("#selectedContainer { background-color: rgb(255,255,255); }");
    scrollArea->setWidget(selectedContainer);

    //创建selectedContainer 中的垂直布局 中间会添加元素
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    vlayout->setAlignment(Qt::AlignTop);
    selectedContainer->setLayout(vlayout);

    //创建底部按钮  取消和完成
    QString style = "QPushButton { color: rgb(7,191,96); background-color: rgb(240,240,240); border: none; border-radius: 5px; }";
    style += "QPushButton:hover { background-color: rgb(220,220,220); } QPushButton:pressed { background-color: rgb(200,200,200) }";
    //完成按钮
    QPushButton* okBtn = new QPushButton();
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(style);
    //取消按钮
    QPushButton* cancelBtn = new QPushButton();
    cancelBtn->setFixedHeight(40);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(style);

    //添加到布局中
    gridLayout->addWidget(tipLabel,0,0,1,9);
    gridLayout->addWidget(scrollArea,1,0,1,9);
    gridLayout->addWidget(okBtn,2,1,1,3);
    gridLayout->addWidget(cancelBtn,2,5,1,3);

#if 0
    // 此处的数据通过勾选左侧列表来生成.
    QIcon defaultAvatar(":/resource/image/avatarDefault.png");
    for (int i = 0; i < 10; ++i) {
        this->addSelectedFriend(QString::number(1000 + i), defaultAvatar, "张三" + QString::number(i));
    }
#endif

    connect(okBtn, &QPushButton::clicked, this, &ChooseFriendDialog::clickOkBtn);
    connect(cancelBtn, &QPushButton::clicked, this, [=]() {
        this->close();
    });
}

void ChooseFriendDialog::addFriend(const QString& userId,const QIcon& avatar,const QString& name,bool checked)
{
    ChooseFriendItem* item = new ChooseFriendItem(this,userId,avatar,name,checked);
    totalContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::addSelectedFriend(const QString& userId,const QIcon& avatar,const QString& name)
{
    ChooseFriendItem* item = new ChooseFriendItem(this,userId,avatar,name,true);
    //selectedContainer->layout()其实是gridLayout
    selectedContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::deleSeletedFriend(const QString& userId)
{
    //遍历选中的区域(selectedContainer)中是否有userId,如果有就删除
    QVBoxLayout* vlayoutRight  = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    //从后面开始
    for(int i = vlayoutRight->count() -1; i >=0; i--) {
        auto* item = vlayoutRight->itemAt(i);
        //如果布局为空，或者子窗口为空
        if(item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if(chooseFriendItem->getUserId() != userId)  {
            continue;
        }

        vlayoutRight->removeWidget(chooseFriendItem);
        //不能直接使用delete  因为目前状态是在选择好友的窗口中，是另一个窗口，在运行
        chooseFriendItem->deleteLater();
    }

    //遍历左侧，将对应的userId从勾选状态变为不勾选
    QVBoxLayout* vlayoutLeft  = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    for(int i = 0;i < vlayoutLeft->count(); i++) {
        auto* item = vlayoutLeft->itemAt(i);
        //如果布局为空，或者子窗口为空
        if(item == nullptr || item->widget() == nullptr) {
            continue;
        }

        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if(chooseFriendItem->getUserId() != userId)  {
            continue;
        }

        //取消checkBox的选中状态
        chooseFriendItem->getCheckBox()->setChecked(false);
    }
}

void ChooseFriendDialog::clickOkBtn()
{
    // 获取到选中的好友列表
    QList<QString> userIdList = generateMemberList();
    if(userIdList.size() < 3) {
        Toast::showMessage("群聊中的成员不足三个, 无法创建群聊");
        return;
    }

    // 发送网络请求，创建群聊
    DataCenter* dataCenter = DataCenter::getInstance();
    dataCenter->createGroupChatSessionAsync(userIdList);

    this->close();
}

void ChooseFriendDialog::initData()
{
    DataCenter* dataCenter = DataCenter::getInstance();
    QList<UserInfo>* friendList = dataCenter->getFriendList();
    if (friendList == nullptr) {
        LOG() << "加载数据时发现好友列表为空!";
        return;
    }

    for(auto it = friendList->begin(); it != friendList->end(); it++) {
        if (it->userId == this->userId) {
            this->addSelectedFriend(this->userId,it->avatar,it->nickname);
            this->addFriend(it->userId,it->avatar,it->nickname,true);
        } else {
            this->addFriend(it->userId,it->avatar,it->nickname,false);
        }
    }
}

// 获取选中的好友列表
QList<QString> ChooseFriendDialog::generateMemberList()
{
    QList<QString> result;
    DataCenter* dataCenter = DataCenter::getInstance();
    if (dataCenter->getMyself() == nullptr) {
        LOG() << "个人信息尚未加载!";
        return result;
    }

    result.push_back(dataCenter->getMyself()->userId);

    // 遍历选中的好友
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    for(int i =0; i < layout->count(); i++) {
        auto* item = layout->itemAt(i);

        if(item == nullptr || item->widget() == nullptr) {
            continue;
        }

        auto* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        result.push_back(chooseFriendItem->getUserId());
    }

    return result;
}
